package mysocket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class Client {

    public static final String BYEBYE = "byebye";

    public static void main(String[] args) throws Exception {

        Socket socket = null;

        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;

        InputStream inputStream = null;
        DataInputStream dataInputStream = null;

        try{
            socket = new Socket("localhost",8001);

            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);

            inputStream = socket.getInputStream();
            dataInputStream = new DataInputStream(inputStream);

            Scanner scanner = new Scanner(System.in);

            //计数器，当输入输出线程都byebye了之后才断开连接
            CountDownLatch countDownLatch = new CountDownLatch(2);

            DataOutputStream finalDataOutputStream = dataOutputStream;
            new Thread(()->{
                String to = "";
                while (true){
                    to = scanner.next();
                    try {
                        finalDataOutputStream.writeUTF(to);
                        System.out.println("客户端：" + to);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (to.equals(BYEBYE)){
                        countDownLatch.countDown();
                        break;
                    }
                }
            }).start();

            DataInputStream finalDataInputStream = dataInputStream;
            new Thread(()->{
                String from = "";
                while (true){
                    try {
                        from = finalDataInputStream.readUTF();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (!from.equals("")){
                        System.out.println("服务端：" + from);
                    }
                    if (from.equals(BYEBYE)){
                        countDownLatch.countDown();
                        break;
                    }
                }
            }).start();

            countDownLatch.await();
        }finally {
            if (dataInputStream != null){
                dataInputStream.close();
            }
            if (inputStream != null){
                inputStream.close();
            }
            if (dataOutputStream != null){
                dataOutputStream.close();
            }
            if (outputStream != null){
                outputStream.close();
            }
            if (socket != null){
                socket.close();
            }
        }


    }
}
